package org.gianluca.sagrafx;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Slider;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;
import javax.persistence.EntityManagerFactory;
import org.gianluca.sagrafx.entities.Ordini;
import org.gianluca.sagrafx.entities.OrdiniJpaController;
import org.gianluca.sagrafx.entities.Pietanze;
import org.gianluca.sagrafx.entities.PietanzeJpaController;
import org.gianluca.sagrafx.entities.exceptions.NonexistentEntityException;

public class SagraController {

    @FXML
    private ResourceBundle resources;
    @FXML
    private URL location;
    @FXML
    private Slider sliderQuantitaVendute;
    @FXML
    private TabPane tabMainPanel;
    @FXML
    private Tab tabMenuHandling;
    @FXML
    private TableView<Pietanze> tblViewPietanze;
    @FXML
    private TableView<Ordini> tblViewOrdini;
    @FXML
    private TextField txtCosto;
    @FXML
    private TextField txtNomePietanza;
    @FXML
    private TextField txtQuantitaVendute;
    @FXML
    private Button btnDecrementa;
    @FXML
    private Label lblIncasso;
    @FXML
    private Button btnIncrementa;
    @FXML
    private Button btnAddAcqua;
    @FXML
    private Button btnAddBibite;
    @FXML
    private Button btnAddBraciola;
    @FXML
    private Button btnAddCrepe;
    @FXML
    private Button btnAddDolce;
    @FXML
    private Button btnAddFrutta;
    @FXML
    private Button btnAddGramolata;
    @FXML
    private Button btnAddPanino;
    @FXML
    private Button btnAddPasta;
    @FXML
    private Button btnAddPatatine;
    @FXML
    private Button btnRemoveAcqua;
    @FXML
    private Button btnRemoveBibite;
    @FXML
    private Button btnRemoveBraciola;
    @FXML
    private Button btnRemoveCrepe;
    @FXML
    private Button btnRemoveDolce;
    @FXML
    private Button btnRemoveFrutta;
    @FXML
    private Button btnRemoveGramolata;
    @FXML
    private Button btnRemovePanino;
    @FXML
    private Button btnRemovePasta;
    @FXML
    private Button btnRemovePatatine;
    @FXML
    private Button btnTotale;
    @FXML
    private Button btnResto;
    @FXML
    private TextField txtAcqua;
    @FXML
    private TextField txtBibite;
    @FXML
    private TextField txtBraciola;
    @FXML
    private TextField txtCrepe;
    @FXML
    private TextField txtDolce;
    @FXML
    private TextField txtFrutta;
    @FXML
    private TextField txtGramolata;
    @FXML
    private TextField txtPanino;
    @FXML
    private TextField txtPasta;
    @FXML
    private TextField txtPatatine;
    @FXML
    private TextField txtContanti;
    @FXML
    private Label lblTotale;
    @FXML
    private Label lblAcqua;
    @FXML
    private Label lblBibite;
    @FXML
    private Label lblBraciola;
    @FXML
    private Label lblCrepe;
    @FXML
    private Label lblDolce;
    @FXML
    private Label lblGramolata;
    @FXML
    private Label lblFrutta;
    @FXML
    private Label lblPanino;
    @FXML
    private Label lblPasta;
    @FXML
    private Label lblResto;
    @FXML
    private Label lblPatatine;
    @FXML
    private Button btnAzzera;
    @FXML
    private Button btnConfermaOrdine;
    private EntityManagerFactory entityManagerFactory;
    private ObservableList<Pietanze> listPietanze = FXCollections.observableArrayList();
    private ObservableList<Ordini> listOrdini = FXCollections.observableArrayList();
    private PietanzeJpaController pietanzeJpaController;
    private OrdiniJpaController ordiniJpaController;
    private Map<TextField, Double> costoMap;

    private void updateTableViewPietanze() {
        tblViewPietanze.getColumns().get(0).setVisible(false);
        tblViewPietanze.getColumns().get(0).setVisible(true);
    }

    private void updateTableOrdini() {
        tblViewOrdini.getColumns().get(0).setVisible(false);
        tblViewOrdini.getColumns().get(0).setVisible(true);
    }

    private void initializeTableViewOrdini() {
        listOrdini.addAll(ordiniJpaController.findOrdiniEntities());

        TableColumn tableColumnTimeStamp;
        tableColumnTimeStamp = new TableColumn("Data/Ora");

        TableColumn tableColumnPietanza;
        tableColumnPietanza = new TableColumn("Pietanza");

        TableColumn tableColumnVenduti;
        tableColumnVenduti = new TableColumn("Quantita");

        tblViewOrdini.getColumns().addAll(tableColumnTimeStamp, tableColumnPietanza, tableColumnVenduti);
        tblViewOrdini.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        tblViewOrdini.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

        tableColumnTimeStamp.setCellValueFactory(new Callback<CellDataFeatures<Ordini, String>, ObservableValue<String>>() {
            public ObservableValue<String> call(CellDataFeatures<Ordini, String> ordine) {
                // p.getValue() returns the Person instance for a particular TableView row
                SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
                Date resultdate = new Date(ordine.getValue().getTimestamp().longValue());

                SimpleStringProperty date = new SimpleStringProperty(sdf.format(resultdate));
                return date;
            }
        });

        tableColumnVenduti.setCellValueFactory(new PropertyValueFactory<Ordini, BigInteger>("quantita"));

        tableColumnPietanza.setCellValueFactory(new Callback<CellDataFeatures<Ordini, String>, ObservableValue<String>>() {
            public ObservableValue<String> call(CellDataFeatures<Ordini, String> ordine) {
                // p.getValue() returns the Person instance for a particular TableView row
                SimpleStringProperty nome = new SimpleStringProperty(ordine.getValue().getIdPietanza().getNome());
                return nome;
            }
        });

        tblViewOrdini.setItems(listOrdini);

    }

    public enum Operation {

        ADD, SUB;
    }

    @FXML
    void initialize() {
        assert btnAddAcqua != null : "fx:id=\"btnAddAcqua\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddBibite != null : "fx:id=\"btnAddBibite\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddBraciola != null : "fx:id=\"btnAddBraciola\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddCrepe != null : "fx:id=\"btnAddCrepe\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddDolce != null : "fx:id=\"btnAddDolce\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddFrutta != null : "fx:id=\"btnAddFrutta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddGramolata != null : "fx:id=\"btnAddGramolata\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddPanino != null : "fx:id=\"btnAddPanino\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddPasta != null : "fx:id=\"btnAddPasta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAddPatatine != null : "fx:id=\"btnAddPatatine\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnAzzera != null : "fx:id=\"btnAzzera\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnDecrementa != null : "fx:id=\"btnDecrementa\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnIncrementa != null : "fx:id=\"btnIncrementa\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemoveAcqua != null : "fx:id=\"btnRemoveAcqua\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemoveBibite != null : "fx:id=\"btnRemoveBibite\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemoveBraciola != null : "fx:id=\"btnRemoveBraciola\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemoveCrepe != null : "fx:id=\"btnRemoveCrepe\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemoveDolce != null : "fx:id=\"btnRemoveDolce\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemoveFrutta != null : "fx:id=\"btnRemoveFrutta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemoveGramolata != null : "fx:id=\"btnRemoveGramolata\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemovePanino != null : "fx:id=\"btnRemovePanino\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemovePasta != null : "fx:id=\"btnRemovePasta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnRemovePatatine != null : "fx:id=\"btnRemovePatatine\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnTotale != null : "fx:id=\"btnTotale\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnResto != null : "fx:id=\"btnResto\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblIncasso != null : "fx:id=\"lblIncasso\" was not injected: check your FXML file 'sagra.fxml'.";
        assert sliderQuantitaVendute != null : "fx:id=\"sliderQuantitaVendute\" was not injected: check your FXML file 'sagra.fxml'.";
        assert tabMainPanel != null : "fx:id=\"tabMainPanel\" was not injected: check your FXML file 'sagra.fxml'.";
        assert tabMenuHandling != null : "fx:id=\"tabMenuHandling\" was not injected: check your FXML file 'sagra.fxml'.";
        assert tblViewPietanze != null : "fx:id=\"tblViewPietanze\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtAcqua != null : "fx:id=\"txtAcqua\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtBibite != null : "fx:id=\"txtBibite\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtBraciola != null : "fx:id=\"txtBraciola\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtCosto != null : "fx:id=\"txtCosto\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtCrepe != null : "fx:id=\"txtCrepe\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtDolce != null : "fx:id=\"txtDolce\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtFrutta != null : "fx:id=\"txtFrutta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtGramolata != null : "fx:id=\"txtGramolata\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtNomePietanza != null : "fx:id=\"txtNomePietanza\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtPanino != null : "fx:id=\"txtPanino\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtPasta != null : "fx:id=\"txtPasta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtPatatine != null : "fx:id=\"txtPatatine\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtQuantitaVendute != null : "fx:id=\"txtQuantitaVendute\" was not injected: check your FXML file 'sagra.fxml'.";
        assert txtContanti != null : "fx:id=\"txtContanti\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblTotale != null : "fx:id=\"lblTotale\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblAcqua != null : "fx:id=\"lblAcqua_Vino\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblBibite != null : "fx:id=\"lblBibite\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblBraciola != null : "fx:id=\"lblBraciola\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblCrepe != null : "fx:id=\"lblCrepe\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblDolce != null : "fx:id=\"lblDolce\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblGramolata != null : "fx:id=\"lblGramolata\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblPanino != null : "fx:id=\"lblPanino\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblPasta != null : "fx:id=\"lblPasta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblPatatine != null : "fx:id=\"lblPatatine\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblFrutta != null : "fx:id=\"lblFrutta\" was not injected: check your FXML file 'sagra.fxml'.";
        assert lblResto != null : "fx:id=\"lblResto\" was not injected: check your FXML file 'sagra.fxml'.";
        assert btnConfermaOrdine != null : "fx:id=\"btnConfermaOrdine\" was not injected: check your FXML file 'sagra.fxml'.";
        assert tblViewOrdini != null : "fx:id=\"tblViewOrdini\" was not injected: check your FXML file 'sagra.fxml'.";

        try {
            entityManagerFactory = javax.persistence.Persistence.createEntityManagerFactory(("sagraFX"));
            pietanzeJpaController = new PietanzeJpaController(entityManagerFactory);
            ordiniJpaController = new OrdiniJpaController(entityManagerFactory);
            costoMap = new HashMap<TextField, Double>();

            initializeTitledPaneInserisci();
            initializeTableViewPietanze();
            initializeMenuButton();
            initializeTableViewOrdini();
        } catch (Exception e) {
        }
        initializeMenu();
    }
    
    private void initializeTableViewPietanze() {

        listPietanze.addAll(pietanzeJpaController.findPietanzeEntities());

        TableColumn tableColumnNome;
        tableColumnNome = new TableColumn("Pietanza");

        TableColumn tableColumnCosto;
        tableColumnCosto = new TableColumn("Costo");

        TableColumn tableColumnVenduti;
        tableColumnVenduti = new TableColumn("Venduti");

        tblViewPietanze.getColumns().addAll(tableColumnNome, tableColumnCosto, tableColumnVenduti);
        tblViewPietanze.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        tblViewPietanze.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

        tableColumnNome.setCellValueFactory(new PropertyValueFactory<Pietanze, String>("nome"));
        tableColumnCosto.setCellValueFactory(new PropertyValueFactory<Pietanze, BigDecimal>("costo"));
        tableColumnVenduti.setCellValueFactory(new PropertyValueFactory<Pietanze, Integer>("venduti"));

        tblViewPietanze.setItems(listPietanze);

        tblViewPietanze.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Pietanze>() {
            public void changed(ObservableValue<? extends Pietanze> ov, Pietanze t, Pietanze t1) {
                Pietanze pietanza = t1;
                tblViewPietanze.getSelectionModel().getSelectedItems().get(0);
                txtNomePietanza.setText(pietanza.getNome());
                txtCosto.setText(pietanza.getCosto().toString());
                txtQuantitaVendute.setText(Integer.toString(pietanza.getVenduti()));
                btnIncrementa.setDisable(false);
                btnDecrementa.setDisable(false);
            }
        });

    }

    private void initializeTitledPaneInserisci() {

        updateIncasso();
        txtQuantitaVendute.setText("0");

        btnIncrementa.setDisable(true);
        btnDecrementa.setDisable(true);

        sliderQuantitaVendute.valueProperty().addListener(new ChangeListener<Number>() {
            public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) {
                txtQuantitaVendute.setText(Integer.toString(newValue.intValue()));
            }
        });

        txtQuantitaVendute.textProperty().addListener(new ChangeListener<String>() {
            public void changed(ObservableValue<? extends String> ov, String t, String t1) {
                Integer value = 0;

                try {
                    value = Integer.parseInt(t1);
                } catch (NumberFormatException e) {
                    txtQuantitaVendute.setText("0");
                }

                sliderQuantitaVendute.setValue(value);
            }
        });
    }

    private void initializeMenuButton() {
        btnIncrementa.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                try {
                    int quantita = Integer.parseInt(txtQuantitaVendute.getText());
                    incrementVenduti(quantita);
                    updateIncasso();

                } catch (NonexistentEntityException ex) {
                    Logger.getLogger(SagraController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(SagraController.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });

        btnDecrementa.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                try {
                    int quantita = Integer.parseInt(txtQuantitaVendute.getText());
                    incrementVenduti(-quantita);
                    updateIncasso();

                } catch (NonexistentEntityException ex) {
                    Logger.getLogger(SagraController.class.getName()).log(Level.SEVERE, null, ex);
                } catch (Exception ex) {
                    Logger.getLogger(SagraController.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });


    }

    private void incrementVenduti(int quantita) throws Exception {
        Pietanze pietanza = tblViewPietanze.getSelectionModel().getSelectedItem();

        quantita += pietanza.getVenduti();

        if (quantita < 0) {
            quantita = 0;
        }

        pietanza.setVenduti(quantita);
        pietanzeJpaController.edit(pietanza);
        updateTableViewPietanze();
    }

    private void updateIncasso() {
        final List<Pietanze> pietanze = pietanzeJpaController.findPietanzeEntities();

        double incasso = 0;
        for (Pietanze pietanza : pietanze) {
            incasso += pietanza.getVenduti() * pietanza.getCosto().doubleValue();
        }

        lblIncasso.setText(String.format("Incasso %2.2f euro", incasso));
    }

    private void initializeMenu() {

        costoMap.put(txtAcqua, Double.valueOf(0.50));
        costoMap.put(txtBibite, Double.valueOf(1.50));
        costoMap.put(txtBraciola, Double.valueOf(3.50));
        costoMap.put(txtCrepe, Double.valueOf(2.00));
        costoMap.put(txtDolce, Double.valueOf(1.00));
        costoMap.put(txtFrutta, Double.valueOf(1.50));
        costoMap.put(txtGramolata, Double.valueOf(1.00));
        costoMap.put(txtPanino, Double.valueOf(3.50));
        costoMap.put(txtPasta, Double.valueOf(3.50));
        costoMap.put(txtPatatine, Double.valueOf(1.50));

        Button[] buttons = new Button[]{
            btnAddAcqua, btnAddBibite, btnAddBraciola, btnAddCrepe, btnAddDolce, btnAddFrutta, btnAddGramolata, btnAddPanino, btnAddPasta, btnAddPatatine,
            btnRemoveAcqua, btnRemoveBibite, btnRemoveBraciola, btnRemoveCrepe, btnRemoveDolce, btnRemoveFrutta, btnRemoveGramolata, btnRemovePanino, btnRemovePasta, btnRemovePatatine};

        final TextField[] textFields = new TextField[]{
            txtAcqua, txtBibite, txtBraciola, txtCrepe, txtDolce, txtFrutta, txtGramolata, txtPanino, txtPasta, txtPatatine};

        final Label[] labels = new Label[]{
            lblAcqua, lblBibite, lblBraciola, lblCrepe, lblDolce, lblFrutta, lblGramolata, lblPanino, lblPasta, lblPatatine};

        for (int i = 0; i < textFields.length; i++) {

            buttons[i].setOnAction(createBtnHandler(textFields[i], labels[i], Operation.ADD));
            buttons[i + textFields.length].setOnAction(createBtnHandler(textFields[i], labels[i], Operation.SUB));
            final TextField text = textFields[i];
            final ChangeListener<String> textNumberChangeListener = new ChangeListener<String>() {
                public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) {

                    int value;
                    try {
                        value = Integer.parseInt(newValue);
                    } catch (NumberFormatException exception) {
                        text.setText(oldValue);
                    }
                }
            };
            text.textProperty().addListener(textNumberChangeListener);
        }

        final TextField text = txtContanti;
        final ChangeListener<String> textNumberChangeListener = new ChangeListener<String>() {
            public void changed(ObservableValue<? extends String> ov, String oldValue, String newValue) {

                try {
                    double value = Double.parseDouble(newValue);
                } catch (NumberFormatException exception) {
                    text.setText(oldValue);
                }
            }
        };
        text.textProperty().addListener(textNumberChangeListener);
        text.focusedProperty().addListener(new ChangeListener<Boolean>() {

            public void changed(ObservableValue<? extends Boolean> ov, Boolean oldValue, Boolean newValue) {
                if (newValue) {
                    text.selectAll();
                }
            }
            
        });

        btnTotale.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {

                double tot = 0;
                for (TextField textField : textFields) {
                    tot += costoMap.get(textField) * Double.valueOf(textField.getText());
                }
                lblTotale.setText(String.format("%2.2f euro", tot));
                btnConfermaOrdine.setDisable(false);
            }
        });

        btnAzzera.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                for (int i = 0; i < textFields.length; i++) {
                    textFields[i].setText("0");
                    labels[i].setText(String.format("%2.2f euro", 0.0));
                }
                lblTotale.setText(String.format("%2.2f euro", 0.0));
                lblResto.setText(String.format("%2.2f euro", 0.0));
                txtContanti.setText("0.00");
            }
        });

        btnConfermaOrdine.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {

                try {
                    Date date = new Date();
                    for (int i = 0; i < textFields.length; i++) {
                        final Integer quantita = Integer.parseInt(textFields[i].getText());
                        if (quantita > 0) {
                            Ordini ordine = new Ordini();
                            ordine.setTimestamp(BigInteger.valueOf(date.getTime()));
                            List<Pietanze> pietanzaList = pietanzeJpaController.findPietanzeEntities();
                            for (Pietanze pietanza : pietanzaList) {
                                if (labels[i].getId().equals("lbl" + pietanza.getNome())) {
                                    ordine.setIdPietanza(pietanza);
                                    int venduti = pietanza.getVenduti();
                                    pietanza.setVenduti(venduti + quantita);
                                    try {
                                        pietanzeJpaController.edit(pietanza);
                                        int position = listPietanze.indexOf(pietanza);
                                        listPietanze.set(position, pietanza);
                                        listOrdini.add(ordine);
                                        updateTableViewPietanze();
                                        updateTableOrdini();
                                        updateIncasso();
                                    } catch (NonexistentEntityException ex) {
                                        Logger.getLogger(SagraController.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (Exception ex) {
                                        Logger.getLogger(SagraController.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    break;
                                }
                            }
                            ordine.setQuantita(quantita);
                            ordiniJpaController.create(ordine);
                        }
                    }
                } catch (Exception e) {
                    System.out.println("Exception for order confimation");
                }

                btnAzzera.fire();
                btnConfermaOrdine.setDisable(true);
            }
        });

        btnResto.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent evt) {

                String totale = lblTotale.getText().replace("euro", "");
                totale = totale.replace(",", ".");

                double resto = Double.parseDouble(txtContanti.getText()) - Double.parseDouble(totale);

                lblResto.setText(String.format("%2.2f euro", resto));
            }
        });
    }

    private EventHandler<ActionEvent> createBtnHandler(final TextField text, final Label label, final Operation operation) {
        EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {

                Integer value = Integer.parseInt(text.getText());
                switch (operation) {
                    case ADD:
                        value++;
                        break;
                    case SUB:
                        value--;
                        break;
                }
                text.setText(value.toString());
                final Double costo = costoMap.get(text);
                label.setText(String.format("%2.2f euro", value * costo));
            }
        };

        return handler;
    }
}
